#!/usr/bin/env python

"Internet Time Protocol - TCP client"

import sys
import socket
import logging
import time
import struct

logging.basicConfig(level=logging.INFO)

HOSTNAME='localhost'
PORT=3737
TIME1970 = 2208988800

def main():
    service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    logging.info("Connecting on server '%s' port %d" % (HOSTNAME, PORT))
    service.connect((HOSTNAME, PORT))
    logging.info("Connected")
    logging.info("Reading data...")
    t = service.recv(4)
    service.close()
    logging.info("Disconnected")
    t = struct.unpack("!I", t)[0]
    t = int(t - TIME1970)
    off = int(time.time()) - t
    logging.info("Server time is " + time.ctime(t))
    logging.info("Local clock is %d seconds off" % off)

if __name__ == '__main__':
    if len(sys.argv) == 2:
        HOSTNAME = sys.argv[1]
    if len(sys.argv) == 3:
        HOSTNAME = sys.argv[1]
        PORT = int(sys.argv[2])
    main()
